<script setup lang="tsx">
defineOptions({
  name: "FULLSCREEN_ELECTRICTITY_OPERATION_OVERVIEW"
});
import { ref, onMounted, onUnmounted, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import { ArrowRightBold } from "@px-ui/icons-vue";
import fullScreen from "@/assets/svg/common/fullScreen.svg?component";
import {
  queryDeviceStatistics,
  getHandoverRecord,
  queryMainStatus,
  queryTotalElectricityStatistics,
  queryloadRateList,
  getSafeDays,
  updateSafeDays
} from "@/api/modules/operation";
import { queryDictData } from "@/api/common";
import { useLabelLayoutBarChartFn, useGetBarChartsAgOptions_new, useGetBarChartsAgOptions } from "@/hooks/useEcharts";
import { useRouterStoreHook } from "@/store/modules/router";
import topBoard from "@/views/common/topBoard/index.vue";
import ApprovalStatus from "@/views/common/handleover/components/ApprovalStatus.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import deviceStatisticsTasks from "@/views/gas/operation/overview/components/deviceStatisticsTasks.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import mainProgressStatus from "./components/mainProgressStatus.vue";
import loadRate from "./components/loadRate.vue";
import safeDays from "./components/safeDays.vue";
import { deviceStatus_ele } from "@/utils/constant";
import { loadingTimeout } from "@/utils/http/constant";
import { useFullscreen, useTransition, TransitionPresets } from "@vueuse/core";
import dayjs from "dayjs";

const route = useRoute();

const { isFullscreen, toggle } = useFullscreen();
const routerStore = useRouterStoreHook();
const height = ref<number>(236);
const shiftScrollbarHeight = computed(() => height.value - 40);
const clock = ref<string>("");
const clickTimer = ref<any>(null);
const operationDays = ref<number>(0);
const isShowSafeDays = ref<boolean>(false);
const updateTimer = ref<any>(null);
const eqpRunStatusList = ref([]);
const topBoardRef = ref();

const operationDaysVal = useTransition(operationDays, {
  duration: 1000,
  transition: TransitionPresets.easeInOutExpo
});

// 市政进线状态
const mainProgressStatusRef = ref<InstanceType<typeof mainProgressStatus> | null>(null);
const mainProgressStatusData = ref<Array<any>>([]);
const mainStatusInit = async () => {
  const params = { classCode: "ELECTRICTITY" };
  const res = await queryMainStatus(params, () => mainProgressStatusRef.value.loadingInstance.close());
  if (res?.length) {
    mainProgressStatusData.value = res;
  }
};

// 总用电量统计
const totalElectricityRef = ref<InstanceType<typeof echartsChart> | null>(null);
const totalElectricityTitle = ref<string>("总用电量统计");
const totalElectricityOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const totalElectricityInit = async () => {
  const res = await queryTotalElectricityStatistics(null, () => totalElectricityRef.value.loadingInstance.close());
  if (!res?.length) return;
  const ec = await totalElectricityRef.value.getEcharts();
  const unit = res[0].unit || "kWh";
  const xAxisData = res.map(item => item.usedDay);
  const fabData = res.map(item => item.fabUsedValue);
  const deviceData = res.map(item => item.deviceUsedValue);
  const allUsedData = res.map(item => item.allUsedValue);
  const label = {
    show: true,
    position: "top",
    formatter(params) {
      const { dataIndex = 0 } = params;
      if (typeof dataIndex !== "number") return "";
      const { allUsedValue = 0 } = res[dataIndex];
      if (typeof allUsedValue !== "number") return "";
      return allUsedValue;
    }
  };
  const legend = {
    show: true,
    right: 0
  };
  const tooltip: any = {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  };
  const xAxis = [
    {
      type: "category",
      data: xAxisData
      // axisLabel: {
      //   interval: 0
      // }
    }
  ];
  const series: Array<any> = [
    {
      name: "总电量",
      type: "line",
      label: { show: false },
      symbol: "circle",
      symbolSize: 8,
      emphasis: { focus: "series" },
      data: allUsedData,
      itemStyle: {
        color: "#FFCA45FF"
      }
    },
    {
      name: "机台用电",
      type: "bar",
      stack: "Ad",
      emphasis: { focus: "series" },
      data: fabData,
      barWidth: 30,
      itemStyle: {
        color: "#00C2FFFF"
      }
    },
    {
      name: "厂务用电",
      type: "bar",
      stack: "Ad",
      emphasis: { focus: "series" },
      data: deviceData,
      barWidth: 30,
      itemStyle: {
        color: "#04FF9DFF"
      }
    }
  ];
  const backgroundColor = "transparent";
  const ag = { legend, tooltip, xAxis, series, backgroundColor };
  totalElectricityOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, fabData, totalElectricityTitle.value, unit, null, false, "top", ag);
  totalElectricityRef.value.loadingInstance.close();
};

// 负载率
const loadRateRef = ref<InstanceType<typeof loadRate> | null>(null);
const loadRateData = ref<Array<any>>([]);
const loadRateInit = async () => {
  const res = await queryloadRateList(null, () => loadRateRef.value.loadingInstance.close());
  if (!res?.length) return;
  loadRateData.value = res;
};

// 交接班 （目前显示截数据，真实接口未出 2024-6-14）
const shiftTableRef = ref<InstanceType<typeof commonTable> | null>(null);
const shiftTableCloumns = ref<Array<CommonTable.TableCloumnsType>>([
  {
    label: "交接内容",
    prop: "moduleName",
    width: 100
  },
  {
    label: "责任人",
    prop: "handoverPersonNames",
    width: 100,
    render({ row }: any) {
      const { handoverPersonNames = [] } = row;
      if (handoverPersonNames?.length) {
        return () => handoverPersonNames.join(", ");
      } else {
        return () => "--";
      }
    }
  },
  {
    label: "状态",
    prop: "handoverStatus",
    width: 100,
    render({ row }: any) {
      const { handoverStatus = "" } = row;
      return () => (
        <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
          <ApprovalStatus status={handoverStatus || "UN_SUBMITTED"} />
        </div>
      );
    }
  }
]);
const shiftHeaderCellStyle = row => {
  const { columnIndex } = row;
  if (columnIndex === 2) {
    return {
      "text-align": "center"
    };
  } else {
    return null;
  }
};
const shiftList = reactive<Array<any>>([]);
const shiftInit = async () => {
  shiftList.splice(0);
  const {
    query: { className = "" }
  } = route;
  const res = await getHandoverRecord(className as string, () => {
    shiftTableRef.value.loading = false;
  });
  if (res?.length) {
    shiftList.push(...res);
  }
  shiftTableRef.value.loading = false;
};

const initLoading = () => {
  mainProgressStatusRef.value?.initLoading();
  totalElectricityRef.value?.initLoading();
  loadRateRef.value?.initLoading();
  shiftTableRef.value.loading = true;
};

const closeLoading = () => {
  setTimeout(() => {
    shiftTableRef.value?.loading && (shiftTableRef.value.loading = false);
  }, loadingTimeout);
};

const startClock = () => {
  clearClock();
  clickTimer.value = setInterval(async () => {
    clock.value = dayjs().format("YYYY/MM/DD HH:mm:ss");
    const hour = dayjs().get("hour");
    const minute = dayjs().get("minute");
    const second = dayjs().get("second");
    if (hour === 23 && minute === 59 && second === 59) {
      operationDays.value += 1;
      const id = 1;
      const params = { id, num: operationDays.value };
      await updateSafeDays(params);
    }
  }, 1000);
};
const clearClock = () => {
  clearInterval(clickTimer.value);
};

const getSafeDaysFn = async () => {
  const res = await getSafeDays(1);
  if (!res) return;
  const { num } = res;
  operationDays.value = num;
};

const init = async () => {
  const title = "平台概览（电科运维）";
  document.title = title;
  startClock();
  await getSafeDaysFn();
};

const toFullScreen = () => {
  toggle();
};

const update = (delay: number) => {
  clearUpdate();
  updateTimer.value = setInterval(() => {
    topBoardRef?.value?.initAll();
    // 市政进线状态
    mainStatusInit().then(() => {
      mainProgressStatusRef.value.updateEchartsOption();
    });
    // 总用电量统计
    totalElectricityInit().then(() => {
      totalElectricityRef.value.updateEchartsOption();
      // totalElectricityRef.value.forceUpdateEcharts();
    });
    // 负载率
    loadRateInit().then(() => {
      loadRateRef.value.updateEchartsOption();
    });
    // 交接班
    shiftInit();
  }, delay);
};

const clearUpdate = () => {
  clearInterval(updateTimer.value);
};

onMounted(async () => {
  await init();
  initLoading();
  closeLoading();

  // 市政进线状态
  mainStatusInit().then(() => {
    mainProgressStatusRef.value.loadingInstance.close();
  });
  // 总用电量统计
  totalElectricityInit();
  // 负载率
  loadRateInit().then(() => {
    loadRateRef.value.loadingInstance.close();
  });
  // 交接班
  shiftInit();
  // 更新数据（30s）
  const delay = 1000 * 30;
  update(delay);
});

onUnmounted(() => {
  clearClock();
  clearUpdate();
});
</script>

<template>
  <div class="gas-overview">
    <div class="gas-overview-item one">
      <div class="one-item">{{ clock }}</div>
      <div class="one-item one-middle">电科运维平台概览</div>
      <div class="one-item one-right">
        <div class="one-days" @click="isShowSafeDays = true">安全运行天数：{{ Math.round(operationDaysVal) }}天</div>
      </div>
    </div>

    <div class="gas-overview-item all">
      <topBoard ref="topBoardRef" classCode="ELECTRICTITY" dark :height="height" />
    </div>
    <!-- <div class="gas-overview-item two">
      <echartsChart ref="deviceStatisticsRef" dark :height="height" :title="deviceStatisticsTitle" :options="deviceStatisticsOptions" />
    </div>
    <div class="gas-overview-item three">
      <deviceStatisticsTasks ref="deviceStatisticsTasksRef" dark :height="height" :query-data="deviceStatisticsQueryData" />
    </div>

    <div class="gas-overview-item four">
      <echartsChart ref="alarmStatRef" dark :height="height" :title="alarmStatTitle" :options="alarmStatOptions" />
    </div> -->

    <div class="gas-overview-item five">
      <modelBox title="市政进线状态" dark>
        <mainProgressStatus ref="mainProgressStatusRef" dark :data="mainProgressStatusData" />
      </modelBox>
    </div>

    <div class="gas-overview-item six">
      <echartsChart ref="totalElectricityRef" dark :height="height" :title="totalElectricityTitle" :options="totalElectricityOptions" />
    </div>

    <div class="gas-overview-item seven">
      <modelBox title="负载率" dark>
        <loadRate ref="loadRateRef" dark :data="loadRateData" />
      </modelBox>
    </div>

    <div class="gas-overview-item eight">
      <modelBox title="交接班" dark>
        <commonTable
          ref="shiftTableRef"
          mode="stripe"
          dark
          :border="false"
          :pagination="false"
          :image-size="60"
          :height="shiftScrollbarHeight"
          :header-cell-style="shiftHeaderCellStyle"
          :tableCloumns="shiftTableCloumns"
          :list="shiftList"
        />
      </modelBox>
    </div>
    <div v-if="!isFullscreen" class="full-screen">
      <fullScreen class="icon" @click="toFullScreen" />
    </div>
    <safeDays v-if="isShowSafeDays" v-model="operationDays" v-model:visible="isShowSafeDays" />
  </div>
</template>

<style lang="scss" scoped>
.gas-overview {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(24, minmax(16px, 1fr));
  grid-auto-rows: 66px 234px 5fr 5fr;
  grid-auto-flow: column dense;
  grid-gap: 16px;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #001e3bff;

  .full-screen {
    position: absolute;
    top: 6px;
    right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    cursor: pointer;
    background-color: var(--px-color-primary-light-9);
    border-radius: 4px;
    box-shadow: 0 0 4px 0 var(--px-color-primary-light-3);

    .icon {
      width: 70%;
      height: 70%;
      color: var(--px-color-primary);
    }

    &:hover {
      background-color: var(--px-color-primary-light-7);
      box-shadow: none;
    }
  }

  .gas-overview-item {
    display: flex;
    align-items: center;
    justify-content: center;

    .px-button {
      padding-right: 0;
    }
  }

  .one {
    box-sizing: border-box;
    display: flex;
    grid-column: 1 / 25;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    background: url("@/assets/images/overview_header.png") no-repeat;
    background-position: center center;
    background-size: 100% 100%;

    .one-item {
      flex: 1;
      font-size: 18px;
      font-weight: 700;
      line-height: 1;
      color: #fff;
      letter-spacing: 4px;
      background: linear-gradient(to top, #00c2ffff, #fff);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .one-middle {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
    }

    .one-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .one-days {
        &:hover {
          cursor: pointer;
          background: #fff;
          background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
    }
  }

  .all {
    grid-column: 1 / -1;
  }

  .two {
    grid-column: 1 / 7;
  }

  .three {
    grid-column: 7 / 21;
  }

  .four {
    grid-column: 21 / 25;
  }

  .five {
    grid-column: 1 / 19;
  }

  .six {
    grid-column: 19 / 25;
  }

  .seven {
    grid-column: 1 / 19;
  }

  .eight {
    grid-column: 19 / 25;
  }
}

:deep(.echarts-chart-dark, .echarts-chart-dark-noborde) {
  background: transparent;
}
</style>
